#!/bin/bash
#
# This Script will set lower/higer Pentium M/Core/Core2 Voltages
# Original by the gentoo-undervolt-script
# adapted for Debian/Ubuntu
#
# Autor: ballessay          13.05.2006
# Adapted by Brad Midlgey to the new SysFS-Interface
# Distributed under the terms of the GNU General Public License
###################################################################

# points to the config-file
CONFIGURATION="/etc/phc-config/undervolt";
. $CONFIGURATION ;


do_error()
{
  # Display an error
  # $1: Error message

  echo $1 >&2 ;
  echo "see https://www.dedigentoo.org/trac/linux-phc for further information" >&2 ;
  exit 1 ;
}

sysfs_check() 
{
  # Check that the sysfs interface exists

  if ! [ -e ${VTABLE_PATH} ]; then
    echo "SysFs voltage_table not found. Can't modify CPU voltage table. (${VTABLE_PATH})" >&2 ;
    echo "It seems that the undervolting patch has not been applied to the kernel" >&2 ;
    do_error "or that the file /etc/conf.d/undervolt is not correctly configured." >&2 ;
    return 1 ;
  fi
}

einfo_tables()
{
  # display current table and a custom table
  # $1 : custom table to display

  # Display the voltage table currently used by the CPU
  echo "Current table:     "`cat ${VTABLE_PATH} ` ;

  # Display the custom voltage table
  echo "Configured table:  ${1}" ;
}

set_custom_table()
{
  # Set a custom table through the sysfs interface
  # $1 : custom table to set

  # Display current table and custom table that will be set
  einfo_tables "${1}" ;

  # Write the custom voltage to the SysFS interface and display the
  # new voltage table that is now used by the CPU if there is no error
  echo "${1}" > ${VTABLE_PATH} && \
  echo "Applied table:     "`cat ${VTABLE_PATH}` ;

  return $?
}


case "$1" in
	start)	echo "change CPU Voltage Table" ;
		if [ "$IS_CONFIGURED" = "yes" ]; then
			sysfs_check || return 1 ;

			set_custom_table "${CUSTOM_VTABLE}" ;
    			exit $? ;
		else
			do_error "Custom voltage table is not configured. Check the file /etc/conf.d/undervolt" ;
		fi
		;;

	stop)	if [ "$SWITCH_BACK" = "yes" ]; then
			if [ "$IS_CONFIGURED" = "yes" ]; then
				echo "Switching back to default CPU voltage table" ;

				sysfs_check || return 1 ;

				set_custom_table "${DEFAULT_VTABLE}" ;
				exit 0 ;
			else
				do_error "Default voltage table is not configured. Check the file /etc/conf.d/undervolt"
			fi
		else
			echo "Not switching back to default CPU voltage table (disabled in configuration)" ;
		exit 0
		fi 
		;;
	*)	echo "Usage: $N {start|stop}" >&2;
		exit 1;
		;;
esac

exit 0;
